package org.example

import org.example.common.DButils

class UserOper {
  case class User(id: Int, username: String, password: String, isvlid: Int)

  def Select(): Unit = {
    val con = DButils.getConn()
    val sql = "select * from sysuser"
    try {
      val ps = con.prepareStatement(sql.toString())
      val t = ps.executeQuery()
      while (t.next()) {
        println("登录名姓名：" + t.getString("username"))
      }
      println(t)
    } catch {
      case ex: Exception => {
        println("读取数据报错")
      }

    } finally {
      DButils.closeCon(con)
    }
  }

  def insertUser(user: User): Boolean = {
    val con = DButils.getConn();
    println("测试添加数据是否成功")
    try {
      val sql = new StringBuilder()
        .append("insert into sysuser (username,password, isvlid)")
        .append("values(?,?,?)")
      val pstm = con.prepareStatement(sql.toString())
      pstm.setObject(1, user.username)
      pstm.setObject(2, user.password)
      pstm.setObject(3, user.isvlid)

      val temp = pstm.executeUpdate()
      if (temp > 0) {
        println("保持成功")
      } else {
        println("保持失败")
      }
    } catch {
      case exception: Exception => {
        println("添加数据时报错")
      }
    } finally {
      DButils.closeCon(con)
    }
    true
  }

  def updateUser(user: User): Unit = {
    var returnValue = false
    val con = DButils.getConn()
    try {
      val sql = "update sysuser set username=?,password=?, isvlid=? where id=?"
      val pstm = con.prepareStatement(sql.toString())

      pstm.setObject(1, user.username)
      pstm.setObject(2, user.password)
      pstm.setObject(3, user.isvlid)
      pstm.setObject(4, user.id)

      val temp = pstm.executeUpdate()
      if (temp > 0) {
        println("更新成功")
        returnValue = true
      } else
        println("失败")
    } catch {
      case exception: Exception => {
        println("更新数据时报错")
      }
    }
  }
}